/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import lights.adapters.Field;
import lights.adapters.Tuple;
import lights.interfaces.ITuple;
import lights.interfaces.IValuedField;
import lime2.Location;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.TupleType;

/**
 * @author Xing Jiankuan
 * 
 */
public abstract class AbstractAgent implements Runnable {

	protected long freq = 0;
	protected double prob = 0;

	protected Long[][] pInfo = null;
	protected String agentName = null;
	private long nextFreq = 0;
	private double nextProb = 0.0;
	boolean isReadAgent = false;

	private Logger LOG = Logger.getLogger(this.getClass().getName());

	/**
	 * 
	 */
	public AbstractAgent(String name, long initialFreq, Long initialProb,
			Long[][] info) {
		agentName = name;
		freq = initialFreq;
		prob = initialProb / 100.0;
		pInfo = info;
		isReadAgent = true;
		initTimer();
	}

	public AbstractAgent(String name, long initialFreq, Long[][] info) {
		agentName = name;
		freq = initialFreq;
		pInfo = info;
		initTimer();
	}

	int index = 0;

	private void initTimer() {
		if (index < pInfo.length) {
			long p = pInfo[index][0];
			nextFreq = pInfo[index][1];
			if (isReadAgent)
				nextProb = pInfo[index][2] / 100.0;
			Timer timer = new Timer();
			TimerTask tt = new FreqTimerTask();
			index++;
			timer.schedule(tt, p * AgentUtil.period);
		}
	}

	class FreqTimerTask extends TimerTask {

		@Override
		public void run() {
			StringBuffer sb = new StringBuffer();
			sb.append(String.format("CHANGE,%s,ofreq=%d,nfreq=%d", agentName,
					freq, nextFreq));
			freq = nextFreq;
			if (isReadAgent) {
				sb.append(String.format(",oprob=%g,nprob=%g", prob, nextProb));
				prob = nextProb;
			}
			LOG.info(sb.toString());

			if (index < pInfo.length) {
				long p2 = pInfo[index][0];
				long p1 = pInfo[index - 1][0];
				nextFreq = pInfo[index][1];
				if (isReadAgent)
					nextProb = pInfo[index][2] / 100.0;
				Timer timer = new Timer();
				TimerTask tt = new FreqTimerTask();
				index++;
				timer.schedule(tt, (p2 - p1) * AgentUtil.period);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		Thread.currentThread().setName(agentName);
	}

	public abstract void updateList(ListTuple lt);

	public abstract TupleType getType();

	public abstract Location getTargetLocation();

	static FlatShareTuple makeNewTuple(TupleType type, byte[] data) {
		ITuple it = new Tuple();
		it.add(new Field().setValue("switch"));
		it.add(new Field().setValue(data));
		FlatShareTuple a = new FlatShareTuple(type, it);

		return a;
	}

	void rest(long delay) {
		long sleeptime = 0;
		long meaninterval = freq;
		if (meaninterval - delay > 10) {
			sleeptime = meaninterval - delay;
		} else {
			if (meaninterval - delay <= 10 || delay - meaninterval <= 10)
				sleeptime = 0;
			else {
				long temp = (delay / meaninterval + 1);
				sleeptime = meaninterval * temp - delay;
			}
		}

		if (sleeptime > 0) {
			try {
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}

	}

	public void setAgentName(String name) {
		agentName = name;
	}

	public String getAgentName() {
		return agentName;
	}

	public void sleepWait(long millisec) {
		try {
			Thread.sleep(millisec);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Retrieve the data size in the FlatShareTuple which was created by
	 * OutAgent{@link makeNewTuple}
	 * 
	 * @param fst
	 * @return the tuple size
	 * @author Xing Jiankuan
	 */
	public static int retriveDataSizeInTuple(FlatShareTuple fst) {
		IValuedField f = (IValuedField) fst.getTuple().get(1);
		byte[] data = (byte[]) f.getValue();
		return data.length;
	}
}
